package com.example.mybrowser;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

public class ResourceSocketThread extends Thread  
{
	private String Android_ID;
	private Object threadlock;
	private boolean threadlockflag;
	private MobileCache mobileCache;
	private int webState;
	
	private MyHandler handler;
	private Socket socket;
	private String resource;

	public ResourceSocketThread(Socket _socket, MyHandler _handler, MobileCache _mobileCache, int _webState, String _Android_ID)
	{
		threadlock = new Object();
		socket = _socket;
		handler = _handler;
		mobileCache = _mobileCache;
		webState = _webState;
		Android_ID = _Android_ID;
	}
	
	private void WriteResource(String _res)
	{
		resource = _res;
	}
	
	private void pausethread()
	{
        synchronized (threadlock) 
        {
           try
           {
              threadlock.wait() ;
           }catch(Exception e){
        	   e.printStackTrace();
           }
        }

	}
	private void getFromHTML()
	{
		int count = 0;
		byte[] buffer = new byte[20480];
		byte[] msg = new byte[800000];
		String webstring = null;
		String x = null;
		InputStream is = null;
		Socket socket2Server = null;
		PrintWriter out2 = null;
		DataInputStream Webinput = null;
		DataOutputStream Browseroutput = null;
		String FullURL = null;
		String tempstr = null;
		PostMethod post2Server = null;
		
		int length = 0;
		
		try {
			is = socket.getInputStream();

			is.read(buffer);
			
			//is.close();
			
			x=new String(buffer);
			x = x.substring(0, x.indexOf("\r\n\r\n")+4);
			try
			{
				String[] httprequestdata = x.split("\r\n");
				String[] host = httprequestdata[1].split(" ");
				FullURL = httprequestdata[0].split(" ")[1];
				x=x.replace(host[1], "thehostOMGOMGOMG");
				x=x.replace("http://thehostOMGOMGOMG", "");
				x=x.replace("thehostOMGOMGOMG", host[1]);
				// 
				if (false)
				{
					msg = new byte[800000];
					socket2Server = new Socket(host[1], 80);
					Webinput = new DataInputStream(socket2Server.getInputStream()); 
					Browseroutput = new DataOutputStream(socket.getOutputStream()); 
					PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket2Server.getOutputStream())), true);

					out.println(x);
					int HTTPHeader;
				    for (HTTPHeader=0;(count = Webinput.read(msg, length, 800000-length)) > 0;HTTPHeader++) 
				    {
				    	System.out.println("GetFromNet"+HTTPHeader);
				    	
				    	Browseroutput.write(msg, length, count);
				    	
				    	System.out.println("PushToDev"+HTTPHeader);
				    	
				    	length += count;
				    }
				}
				else 
				{
					/*
					x=x.replace(host[1], "192.168.0.150");
					int space1 = x.indexOf(' ', 0);
					int space2 = x.indexOf(' ', space1+1);
					String repString = x.substring(space1, space2);
					x=x.replace(repString, " /MyServlet/MyServlet");
					x=x.replace("\r\n\r\n", "\r\nFULLHOST: "+host[1]+"\r\nREQURL: "+FullURL.replace("http://"+host[1], "")+"\r\nAndroidID: "+ Android_ID + "\r\n\r\n\0");
					*/
					HttpClient client = new HttpClient();
					client.getHostConfiguration().setHost(MainActivity.serverIP, MainActivity.serverPort, "http");
					post2Server = new PostMethod("/MyServlet/MyServlet");
					NameValuePair ReqType = new NameValuePair("ReqType", "Web");
					NameValuePair oreq = new NameValuePair("OriginReq", x);
					NameValuePair devid = new NameValuePair("DevID", Android_ID);
					NameValuePair hostpair = new NameValuePair("hostpara", host[1]); 
					
					post2Server.setRequestBody(new NameValuePair[] {ReqType, oreq, devid, hostpair});

					client.executeMethod(post2Server);
				}
			}
			catch (ArrayIndexOutOfBoundsException e)
			{
				e.printStackTrace();
			}
			
			msg = post2Server.getResponseBody();
			
		    Browseroutput = new DataOutputStream(socket.getOutputStream()); 
		    
		    length = msg.length;
		    
		    String RealHeader;

	    	Browseroutput.write(msg, 0, length);
	    	
	    	RealHeader = new String(msg);
	    	RealHeader = RealHeader.substring(0, RealHeader.indexOf("\r\n\r\n")+4);
	    	
		    mobileCache.AddFile(FullURL, RealHeader, msg, RealHeader.length(), length-RealHeader.length());
		    
		    Browseroutput.close(); 
			socket.close();
			
		}
		catch (IOException e) {			
		    try
			{
		    	mobileCache.AddFile(FullURL, webstring, msg, webstring.length(), length-webstring.length());
				Browseroutput.close();
				socket.close();
			}
			catch (IOException e1)
			{
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} 

			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	private void getFromCache()
	{
		byte[] buffer = new byte[20480];
		String x = null;
		InputStream is = null;
		String FullURL = null;
		
		try {
			is = socket.getInputStream();

			is.read(buffer);
			
			//is.close();
			
			x=new String(buffer);
			String[] httprequestdata = x.split("\r\n");
			FullURL = httprequestdata[0].split(" ")[1];

			MyHTTPResponse httpResponse = mobileCache.GetFileContent(FullURL);
			 
			
			PrintWriter outA = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
			DataOutputStream outB = new DataOutputStream(socket.getOutputStream());
			outA.write(httpResponse.header);
			outA.flush();
			
			if (!httpResponse.ResourcePath.equals("NULL"));
			{
				File cacheFile = new File(httpResponse.ResourcePath);
		        FileInputStream fin = new FileInputStream(cacheFile);
		        
		        byte[] msg = new byte[1024];
		        while(fin.read(msg, 0, 1024) > 0) 
			    { 
			      outB.write(msg, 0, 1024);
			    }
			    outB.flush();
			    fin.close();
			}
			
			outA.close();
			outB.close();
			socket.close();
		}
		catch (IOException e) {			

			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	public void run()
	{
		if (webState!=0)
			getFromHTML();
		else
			getFromCache();
	}
}